// pages/tabs/tabs.js
import { GetPlaceListForPage, getPlaceCategoryListAll } from '../../api/home'
import { imageURL } from '../../../utils/request'

Page({
  data: {
    imageURL:'',
    tabs: [], // 分类列表
    activeIndex: 0,
    scrollLeft: 0,

    placeList: [],
    page: 1,
    rows: 10,
    hasMore: true,
    loading: false,

    showAddPopup: false // 收藏弹框
  },

  onLoad() {
    this.setData({imageURL})
    this.loadCategories()
  },

  // 获取分类
  async loadCategories() {
    try {
      const res = await getPlaceCategoryListAll()
      const categories = Array.isArray(res.data.list) ? res.data.list : []

      // 在最前面加一个 "全部"
      const tabs = [{ id: '', name: '全部' }, ...categories]

      this.setData({ tabs })
      this.loadPlaceList()
    } catch (err) {
      console.error('获取分类失败:', err)
    }
  },

  // 获取景点列表
  async loadPlaceList() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({ loading: true })

    try {
      const categoryId = this.data.tabs[this.data.activeIndex]?.place_category_id || ''

      const res = await GetPlaceListForPage({
        page: this.data.page,
        rows: this.data.rows,
        place_category_id: categoryId,
        is_hot: '' // 传空字符串
      })

      const newList = Array.isArray(res.data.list) ? res.data.list : []

      // 拼接图片前缀
      newList.forEach(item => {
        if (item.image && !item.image.startsWith('http')) {
          item.image = imageURL + item.image
        }
      })

      this.setData({
        placeList: [...this.data.placeList, ...newList],
        page: this.data.page + 1,
        hasMore: newList.length === this.data.rows,
        loading: false
      })
    } catch (err) {
      console.error('获取景点列表失败:', err)
      this.setData({ loading: false })
    }
  },

  // 点击切换 Tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      activeIndex: index,
      scrollLeft: (index - 1) * 60,
      placeList: [],
      page: 1,
      hasMore: true
    })
    this.loadPlaceList()
  },

  // 触底加载
  onReachBottom() {
    this.loadPlaceList()
  },

  // 收藏弹框
  openPopup() {
    this.setData({ showAddPopup: true })
  },
  onConfirmCollect(e) {
    console.log('選中的收藏夾：', e.detail.folder)
  },

  goDetails(e){
    const place_id = e.currentTarget.dataset.place_id
    wx.navigateTo({
      url: `/pages/Itinerary/SceneryDetails/SceneryDetails?place_id=${place_id}`,
    })
  },

  goSearch() {
    wx.navigateTo({
      url: '/pages/Itinerary/searchListPlay/searchListPlay'
    })
  }
})
